import { defineStore } from "pinia";
import { store } from "@/store";
import { userType } from "./types";
import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageSession } from "@pureadmin/utils";
import { getLogin, getUserInfo, LoginParams } from "@/api/user";

import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { type DataInfo, setToken, removeToken, sessionKey } from "@/utils/auth";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    // 用户名
    username: storageSession().getItem<DataInfo>(sessionKey)?.username ?? "",
    // 页面级别权限
    roles: storageSession().getItem<DataInfo>(sessionKey)?.roles ?? [],
    userId: storageSession().getItem<any>(sessionKey)?.userId ?? "",
    userInfo: null
  }),
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 登入 */
    async loginByUsername(data: LoginParams) {
      return new Promise((resolve, reject) => {
        getLogin(data)
          .then(data => {
            if (data.code === 200) {
              setToken(data.token);
              resolve(data);
            } else {
              reject("");
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      this.userInfo = null;
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login").then(() => {
        router.go(0);
      });
    },
    // 获取用户信息
    async getUserInfo() {
      const res = await getUserInfo();
      if (res.code === 200) {
        this.userInfo = res.data;
        this.username = res.data.userName;
        this.roles = res.data.roles.map(el => el.roleKey);
        this.userId = res.data.userId;
        storageSession().setItem(sessionKey, {
          roles: this.roles,
          userId: this.userInfo.userId
        });
      }
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
